import socket,select
from helpFunc import *
import json

f = open('con_controlPort.txt','w')
j  = json.dumps({'con_controlPort':con_controlPort,'con_controlPort2':con_controlPort2,
                 'con_controlPort3':con_controlPort3})
f.write(j)
f.close()
import uuid,json
from connc import tcpRe
import hashlib
id = hashlib.md5(str(uuid.uuid1()).encode()).digest()
k = randomStringDigits(con_keyLen).encode()
print('key: '+k.decode())
w = structWrapper()
w.writeArr(con_key)
w.writeArr(id)
w.writeDWord(con_portsNum)
w.writeByte(len(k))
w.writeArr(k)
w.writeDWord(con_maxConn)
w.writeDWord(con_cachePerConn)
w.writeDWord(con_ssPort)
w.writeDWord(serverPackLen)
w.writeDWord(serverSenLen)
w.writeDWord(con_connBufSize)
w.writeDouble(con_packEffectTime)
w.writeDouble(con_timeoutInternal)

while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(w.data, (serverIp, server_port))
    r = select.select([sock],[],[],1)
    if r[0]==[]:
        sock.close()
        continue
    s2 = sock.recv(udpReadLen)
    sock.close()
    st = structWrapper(s2)    
    if st.readArr(16)!= id:        
        continue       
    ports = []
    for i in range(con_portsNum):
        ports.append(st.readWord())
    print ('server starts:',ports)
    break

l = con_iniPorts(2)
t = tcpRe(l[0],l[1],con_maxConn,con_cachePerConn,con_connBufSize)
t.start(cliPackLen,con_packEffectTime,con_timeoutInternal,ports,k)


